<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-01-04 16:42:00
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-08-31 15:26:24
 * @FilePath: \cxl-admin\src\components\searchCompany.vue
-->
<template>
    <el-select
        v-model="name"
        :style="{ width: width }"
        :placeholder="placeholder"
        clearable
        filterable
        remote
        reserve-keyword
        :disabled="disabled"
        :remote-method="remoteMethod"
        :loading="loading"
        @change="onSelectCompany"
    >
        <el-option
            v-for="itemOption in companyOptions"
            :key="itemOption.value"
            :label="itemOption.name"
            :value="itemOption"
        />
    </el-select>
</template>
<script setup lang="ts">
import { selectCompany } from '@/apis/company/audit'
import { reactive, ref, watchEffect } from 'vue'
//监听父级传递的参数
const props = defineProps(['data', 'placeholder'])
//注册父组件回调
const emits = defineEmits(['change'])
//默认的公司名
const name = ref('')
//搜索时显示的loading
const loading = ref(false)
//搜索结果
const companyOptions: any[] = reactive([])
//是否可输入
const disabled = ref(false)
//搜索框宽度
const width = ref('100%')
const placeholder = ref('请输入公司名称选择')

watchEffect(() => {
    disabled.value = props.data.disabled
    name.value = props.data.name
    width.value = props.data.width
    if (props.placeholder) {
        placeholder.value = props.placeholder
    }
    //当情况输入框内容时，列表选项也清空
    if (name.value == '') {
        companyOptions.length = 0
    }
})

/**
 * 监听用户输入的公司名，搜索
 * @param query
 */
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        getCompanyList(query, () => {
            loading.value = false
        })
    }
}

/**
 * 获取公司
 * @param name
 * @param callback
 */
const getCompanyList = (name = '', callback = () => {}) => {
    selectCompany({ current: 1, size: 10, companyParam: name }).then(res => {
        companyOptions.length = 0
        res.data.data.records.map((item: any) => {
            companyOptions.push({ value: item.companyId, name: `${item.companyName}` })
        })
        callback()
    })
}

/**
 * 监听选择的公司
 * @param res
 */
const onSelectCompany = (res: any) => {
    console.log(res)
    emits('change', res)
}
</script>
